package algotithm.leetcode.listnode.test19;

import algotithm.leetcode.listnode.ListNode;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/18-9:20
 * @URL https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 * @Title 19. 删除链表的倒数第 N 个结点
 */
public class Solution {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        int n = 1;
        int m = 2;

        ListNode l2 = new ListNode(1);
        ListNode l3 = new ListNode(2);
        ListNode l4 = new ListNode(3);
        ListNode l5 = new ListNode(4);
        ListNode l6 = new ListNode(5);
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        l5.next = l6;
        l6.next = null;

        Solution solution = new Solution();
        ListNode listNode = solution.removeNthFromEnd(l1, n);
        while (listNode != null) {
            System.out.print(listNode.val + " ");
            listNode = listNode.next;
        }

        System.out.println();

        ListNode listNode2 = solution.removeNthFromEnd(l2, m);
        while (listNode2 != null) {
            System.out.print(listNode2.val + " ");
            listNode2 = listNode2.next;
        }
    }

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head.next == null && n == 1) {
            return null;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode first = head;
        ListNode second = dummy;
        while (n-- > 0) {
            first = first.next;
        }
        while (first != null) {
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return dummy.next;
    }

}
